package db;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class DBUtil {
	
	private static SessionFactory sessionFactory;
	
	public static void iniciarSessionFactory(String config) 
	{
		try 
		{
			Configuration configuration = new Configuration();
			configuration.configure(config);
			StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
			serviceRegistryBuilder.applySettings(configuration.getProperties());
			ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
		    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} 
		catch (Throwable erro) 
		{
			System.err.println(">>>> Erro na inicializacao da SessionFactory : " + erro);
			throw new ExceptionInInitializerError(erro);
		}
	}

	public static SessionFactory getSessionFactory() 
	{
		return sessionFactory;
	}
	
	public static Session getCurrentSession() 
	{
		Session session = sessionFactory.getCurrentSession();
		if (!session.isOpen())
		{
			session = sessionFactory.openSession();
		}
		return session;
	}

}